
// Copyright (c) WanSheng Intelligent Corp. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.


#define LOG_TAG "UTIL"

#include "wa_edge_configs.h"
#include "path.h"
#define PATH_LEN 256



char * api_get_agent_dir(char * path, int len)
{
    snprintf(path, len, "%swa-agent/", get_ams_root_dir());
    return path;
}


char *api_get_group_cfg_path(char *buffer, int buffer_len, char *group, char *cfgname)
{
    char path[PATH_LEN];
    api_get_agent_dir(path, sizeof(path));
    strcat(path, "config/group");
    if(access(path, 0) == 0)
    {
        if(strlen(path) >= (size_t)buffer_len) return NULL;

        strcpy(buffer, path);
        strcat(buffer, "/");
        strcat(buffer, group);
        strcat(buffer, "/");
        strcat(buffer, cfgname);
        return buffer;
    }

    return NULL;
}


char *api_get_device_cfg_path(char *buffer, int buffer_len, char *deviceId)
{
    char path[PATH_LEN];
    api_get_agent_dir(path, sizeof(path));
    strcat(path, "config/device_on_gateway/");
    if(access(path, 0) == 0)
    {
        if(strlen(path) >= (size_t)buffer_len) return NULL;

        strcpy(buffer, path);
        strcat(buffer, deviceId);
        strcat(buffer, "/device.cfg");
        return buffer;
    }
    else
    {
        printf("get_device_cfg_path: %s dir is not present\n", path);
    }

    return NULL;
}


bool api_check_reset_iagent_flag()
{
   char path[PATH_LEN];
    get_plc_framework_root(path, sizeof(path));
    strncat(path, "local-cfg/.reset_local", sizeof(path)-1 );
    return (access(path, F_OK) == 0);
}

bool api_set_reset_iagent_flag(const char * flag)
{
   char path[PATH_LEN];
    get_plc_framework_root(path, sizeof(path));
    strncat(path, "local-cfg/.new_local", sizeof(path)-1 );
    FILE * fp = fopen(path, "w");
    if(fp)
    {
        fputs(flag, fp);
        fclose(fp);
        WARNING2("add : %s", flag);
    }
    else
    {
        WARNING2("open file fail. %d", errno);
    }
    return true;
}


bool api_remove_reset_iagent_flags()
{
    char path[PATH_LEN];
    get_plc_framework_root(path, sizeof(path));
    strncat(path, "local-cfg/.reset_local", sizeof(path)-1 );
    int rc = remove(path);
    if(rc != 0)
    {
        WARNING("remove [%s] fail!",path);
    }

    get_plc_framework_root(path, sizeof(path));
    strncat(path, "local-cfg/.new_local", sizeof(path)-1 );
    if(access(path, F_OK) == 0)
    {
        rc = remove(path);
        if(rc != 0)
        {
            WARNING("remove [%s] fail!",path);
        }    
    }
    return true;

}
